<template>
  <div :class="{'mobile-table mobile-pt mobile-min-height':showMobilePage}" class="mengli-all-order min-fill-page">
    <dataDisplay
      v-loading="statisticsLoading"
      :data-list="[
        {data: statisticsData.orderNum, label: '订单数', icon: icon_6, isMoney: false },
        {data: statisticsData.saleNum / 100, label: '销售额', icon: icon_10 },
        {data: statisticsData.costNum / 100, label: '成本', icon: icon_11 },
        {data: (statisticsData.saleNum - statisticsData.costNum) / 100, label: '毛利', icon: rmb },
      ]"
      class="mobile-data"
      style="margin-bottom:16px;"
    />
    <div v-if="!showMobilePage" style="position:relative;margin-bottom:16px;">
      <FilterTool
        ref="FilterToolRef"
        v-model="paramsObj"
        :filter-list="filterList"
        show-search-btn
        @handelClick="queryClick"
        @queryEmpty="queryEmpty"
        @filterTagStatus="filterTagStatus"
      />
      <div class="opeator-bar">
        <createBtn v-if="hasRouteAuth('mengli:iPOrder:create') || isAdmin" style="margin-right:14px;" @click.native="toCreate" />
        <btnGroup
          v-if="hasRouteAuth('mengli:iPOrder:export') || isAdmin"
          ref="btnGroupRef"
          :list="[{
            label:'导出',exportApi:'/admin/mengli/ipLicense/list/export', exportName:'商务订单列表', beforeExport: exportBeforeExport, type: 'export'
          }]"
        />
      </div>
    </div>
    <div v-loading="listLoading" style="min-height: 300px;">
      <u-table
        v-if="list.items.length > 0"
        ref="allOrderTableRef"
        :data="list.items"
        :row-class-name="tableRowClassName"
        :height="setTableHeight"
        :row-height="rowHeight()"
        :border="true"
        beautify-table
        header-drag-style
        use-virtual
        class="fb-table"
        element-loading-text="加载中..."
        empty-text="暂无数据"
        header-cell-class-name="order-data-header-cell"
        fit
        hightlight-current-row
        @select="selectTable"
        @select-all="selectTable"
        @sort-change="sortMethod">
        <!-- <u-table-column align="left" label="订单类型" width="120">
            <template slot-scope="scope">
              <div>{{ scope.row.orderType | mengliOrderStatus }}</div>
            </template>
          </u-table-column> -->
        <u-table-column align="center" type="selection" width="50" fixed="left" />
        <u-table-column align="left" label="订单编号" min-width="220">
          <template slot-scope="scope">
            <el-tooltip v-if="scope.row.orderNum" class="item" placement="top" effect="dark">
              <div slot="content" style="max-width: 200px;">{{ scope.row.orderNum }}</div>
              <div class="ellipsis" style="cursor:pointer;color: #406EFF;" @click="toDetail(scope.row)">{{ scope.row.orderNum }}</div>
            </el-tooltip>
            <div v-else>--</div>
          </template>
        </u-table-column>
        <u-table-column align="right" label="订单总额(元)" min-width="130" sortable="custom" prop="income">
          <template slot-scope="scope">
            <PriceColumn :real-val="scope.row.income" :price="scope.row.income / 100" />
          </template>
        </u-table-column>
        <!-- <u-table-column align="right" label="供应商分成(元)" width="150" sortable="custom" prop="supplierCost">
          <template slot-scope="scope">
            <PriceColumn :real-val="scope.row.supplierCost" :price="scope.row.supplierCost / 100" />
          </template>
        </u-table-column> -->
        <u-table-column align="right" label="总成本(元)" width="120" sortable="custom" prop="costNote">
          <template slot-scope="scope">
            <PriceColumn :real-val="scope.row.costNote" :price="scope.row.costNote / 100" />
          </template>
        </u-table-column>
        <u-table-column align="right" label="毛利(元)" width="120">
          <template slot-scope="scope">
            <PriceColumn :real-val="scope.row.maori" :price="scope.row.maori / 100" />
          </template>
        </u-table-column>
        <u-table-column align="left" label="收入模式" width="100">
          <template slot-scope="scope">
            <div v-if="scope.row.sharingModel !== null">{{ scope.row.sharingModel | sharingModelType }}</div>
            <div v-else>--</div>
          </template>
        </u-table-column>
        <u-table-column align="left" label="客户名称" min-width="220">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.clientName" />
          </template>
        </u-table-column>
        <u-table-column align="left" label="销售" min-width="110">
          <template slot-scope="scope">
            <CheckUserInfo v-if="scope.row.market" :label="scope.row.market" :user-id="scope.row.marketId" />
            <span v-else>--</span>
          </template>
        </u-table-column>
        <u-table-column align="left" label="标签" width="150">
          <template slot-scope="scope">
            <TagSelect v-model="scope.row.tag" mode="list" />
          </template>
        </u-table-column>
        <u-table-column align="left" label="合作类型" width="160">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.theme" />
          </template>
        </u-table-column>
        <u-table-column align="left" label="合作品类" min-width="110">
          <template slot-scope="scope">
            <el-tooltip v-if="scope.row.area" class="item" placement="top" effect="dark">
              <div slot="content" style="max-width: 200px;">{{ scope.row.area }}</div>
              <div class="ellipsis">{{ scope.row.area }}</div>
            </el-tooltip>
            <div v-else>--</div>
          </template>
        </u-table-column>
        <u-table-column align="left" label="合作期限" min-width="210" sortable="custom" prop="authorizeEndTime">
          <template slot-scope="scope">
            <div v-if="scope.row.authorizeStartTime && scope.row.authorizeEndTime">
              <span>{{ scope.row.authorizeStartTime | format('YYYY/MM/DD') }}</span>
              <span>至</span>
              <span>{{ scope.row.authorizeEndTime | format('YYYY/MM/DD') }}</span>
            </div>
            <span v-else>--</span>
          </template>
        </u-table-column>
        <u-table-column align="left" label="供应商" width="80">
          <template slot-scope="scope">
            <el-tooltip v-if="scope.row.supplier" class="item" placement="top" effect="dark">
              <div slot="content" style="max-width: 200px;">{{ scope.row.supplier }}</div>
              <div class="ellipsis">{{ scope.row.supplier }}</div>
            </el-tooltip>
            <div v-else>--</div>
          </template>
        </u-table-column>
        <u-table-column align="left" label="IP形象" width="200">
          <template slot-scope="scope">
            <el-tooltip v-if="scope.row.ipInfo" class="item" placement="top" effect="dark">
              <div slot="content" style="max-width: 200px;">{{ scope.row.ipInfo }}</div>
              <div class="ellipsis">{{ scope.row.ipInfo }}</div>
            </el-tooltip>
            <div v-else>--</div>
          </template>
        </u-table-column>
        <u-table-column align="left" label="下单日期" width="100" sortable="custom" prop="orderTime">
          <template slot-scope="scope">
            {{ scope.row.orderTime | format('YYYY/MM/DD') }}
          </template>
        </u-table-column>
        <u-table-column align="left" label="创建时间" width="140" sortable="custom" prop="createTime">
          <template slot-scope="scope">
            {{ scope.row.createTime | format('YYYY/MM/DD HH:mm') }}
          </template>
        </u-table-column>
        <u-table-column :width="(hasRouteAuth('mengli:iPOrder:edit') || hasRouteAuth('mengli:iPOrder:delete'))?110:80" align="left" label="操作" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" @click="toDetail(scope.row)"><span style="font-size:14px;">查看</span></el-button>
            <el-dropdown v-if="hasRouteAuth('mengli:iPOrder:edit') || hasRouteAuth('mengli:iPOrder:delete')" trigger="click">
              <div class="el-dropdown-link">
                <el-button type="text"><span style="font-size:14px;">更多<i class="el-icon-arrow-down"/></span></el-button>
              </div>
              <el-dropdown-menu slot="dropdown" style="margin-top:-24px;margin-right:15px;padding: 0;">
                <el-dropdown-item v-if="hasRouteAuth('mengli:iPOrder:edit') || isAdmin" style="width:100px;text-align: center" @click.native="toEdit(scope.row)">
                  <div>编辑</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="hasRouteAuth('mengli:iPOrder:delete') || isAdmin" style="width:100px;text-align: center" @click.native="toDel(scope.row)">
                  <div>删除</div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </u-table-column>
      </u-table>
      <empty-placeholder v-else-if="!list.isInit" style="margin-bottom: 24px" />
    </div>
    <el-row v-if="showMobilePage && list && list.total > 0" type="flex" justify="left">
      <el-pagination
        v-show="list.total > 0"
        :current-page="list.page"
        :page-size="list.perPage"
        :total="list.total"
        :page-sizes="[20, 50, 100, 250, 500]"
        :layout="pageLayout"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </el-row>
    <fixed-pagination v-show="list.total > 0 && !showMobilePage || showMobilePage">
      <template v-if="showMobilePage">
        <FilterTool
          ref="FilterToolRef"
          v-model="paramsObj"
          :filter-list="filterList"
          show-search-btn
          show-mobile-icon
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus"
        />
        <MoreOpeator
          v-if="hasRouteAuth('mengli:iPOrder:export') || isAdmin"
          ref="moreOpeatorRef"
          :list="[
            { label:'导出',
              exportApi:'/admin/mengli/ipLicense/list/export',
              isBeforeExport: true,
              refName: 'templateExportRef',
              exportName:'商务订单列表', beforeExport: exportBeforeExport, type: 'export'}
          ]"
          label="批量操作"
          show-mobile-icon
        />
        <createBtn v-if="hasRouteAuth('mengli:iPOrder:create') || isAdmin" mobile-table @click.native="toCreate" />
      </template>
      <template v-else>
        <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
        <span style="flex:1;"/>
        <el-pagination
          v-show="list.total > 0"
          :current-page="page"
          :page-size="perPage"
          :total="list.total"
          :page-sizes="[20, 50, 100, 250, 500]"
          layout="total, prev, pager, next, sizes, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </template>
    </fixed-pagination>
    <el-dialog
      :visible.sync="dialogVisible"
      :class="{'mobile-el-dialog': showMobilePage}"
      show-close
      append-to-body
      class="small-common-dialog-size dialog-container"
      @close="closeDialog">
      <h2 style="text-align: center">请选择导出分期月份范围</h2>
      <div class="data-picker-box">
        <el-date-picker
          v-model="exportTime"
          unlink-panels
          range-separator="-"
          start-placeholder="开始月份"
          end-placeholder="结束月份"
          type="monthrange"
          size="small"
          format="yyyy/MM" />
      </div>
      <div class="dialog-footer">
        <el-button :disabled="!exportTime" class="ok" type="primary" @click="handleExport">确定</el-button>
        <el-button class="cancel-btn-style" type="info" style="font-size: 16px" @click="closeDialog">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// component
import FilterTool from '@/components/Tool/filter';
import Title from '@/components/Title';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import createBtn from '@/components/Common/baseComponent/createBtn';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
import TagSelect from '@/components/Common/tagSelect';
// api
import { getmengliIpLicense, mengliOrderDel, getIpLicenseStatistics } from '@/api/mengli';
import { showModal } from '@/utils/message';
import { getOrderConfig } from '@/api/mengliOrder';
import { getTagAll } from '@/api/config';
// tool
import { TAG_MODULES } from '@/utils/const';
import { mengliOrderStatus } from '@/filters/status';
import { format } from '@/filters/date';
import { moneyFilter } from '@/filters/number';
import setting from '@/assets/setting.png';
import { hasRouteAuth } from '@/utils/permission';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import { mapState } from 'vuex';
import tableSelections from '@/mixins/tableSelections';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
import { verificationOptions } from '@/views/project/model/selectData';
import icon_6 from '@/assets/dataDisplay/icon_6.png';
import icon_10 from '@/assets/dataDisplay/icon_10.png';
import icon_11 from '@/assets/dataDisplay/icon_11.png';
import rmb from '@/assets/dataDisplay/rmb.png';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';

export default {
  components: { FilterTool, EmptyPlaceholder, Title, createBtn, btnGroup, dataDisplay, MoreOpeator, TagSelect },
  filters: { mengliOrderStatus, format, moneyFilter,
    sharingModelType(type) {
      const obj = {
        '0': '固定',
        '1': '分成',
        '2': '保底+分成'
      };
      return obj[String(type)] || '--';
    }
  },
  mixins: [tableSelections, TableAdaptive, mobileTable],
  data() {
    return {
      icon_6,
      icon_10,
      icon_11,
      rmb,
      TAG_MODULES,
      setting,
      page: 1,
      perPage: 20,
      listLoading: false,
      paramsObj: {},
      list: {
        items: [],
        total: 0,
        isInit: true
      },
      dialogVisible: false,
      exportTime: '',
      tableRefName: 'allOrderTableRef', // 表格的ref名称
      idKey: 'id', // 唯一表示字段
      rangeKeyArr: [{
        attr: 'orderTime',
        start: 'orderStartTime',
        end: 'orderEndTime',
        type: 'time'
      }, {
        attr: 'createTime',
        start: 'createStartTime',
        end: 'createEndTime',
        type: 'time'
      }, {
        attr: 'authorizeStartTime',
        start: 'authorizeStartStartTime',
        end: 'authorizeStartEndTime',
        type: 'time'
      }, {
        attr: 'authorizeEndTime',
        start: 'authorizeEndStartTime',
        end: 'authorizeEndEndTime',
        type: 'time'
      }, {
        attr: 'incomeTime',
        start: 'incomeStartTime',
        end: 'incomeEndTime',
        type: 'time'
      }],
      tagTreeList: [],
      sortType: '',
      sortName: '',
      isUmyTable: true,
      statisticsData: {},
      statisticsLoading: false,
      areaList: [],
      themeList: []
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    isAdmin() {
      return this.userInfo.userName === '管理员';
    },
    filterList() {
      return [
        { keyword: 'sharingModel', name: '收入模式', type: 'select', options: [
          { value: -1, label: '全部' },
          { value: 0, label: '固定' },
          { value: 1, label: '分成' },
          { value: 2, label: '保底+分成 ' }
        ] },
        { keyword: 'orderNum', name: '订单编号', type: 'input', labelWidth: '82px' },
        { keyword: 'clientName', name: '客户名称', type: 'input', labelWidth: '82px' },
        { keyword: 'market', name: '销售', type: 'input', labelWidth: '82px' },
        { keyword: 'supplier', name: '供应商', type: 'input', labelWidth: '82px' },
        { keyword: 'ipFigure', name: 'IP形象', type: 'input', labelWidth: '82px' },
        { keyword: 'ipSeries', name: 'IP系列', type: 'input', labelWidth: '82px' },
        { keyword: 'relatedInvoice', name: '发票关联状态', type: 'select', options: [{ value: 0, label: '待关联' }, { value: 1, label: '已关联' }] },
        { keyword: 'tag', name: '标签', valueName: 'id', labelName: 'name',
          childrenVal: 'item', type: 'cascaderSelect', checkStrictly: false, options: this.tagTreeList,
          multiple: true, filterable: true, collapseTags: true
        },
        { keyword: 'areaId', name: '合作品类', type: 'select', options: this.areaList },
        { keyword: 'themeId', name: '合作类型', type: 'select', options: this.themeList },
        { keyword: 'writeOffStatus', name: '核销状态', type: 'mulSelect', options: verificationOptions },
        { keyword: 'orderTime', name: '下单日期', timeType: 'daterange', labelWidth: '82px', type: 'rangeDate' },
        { keyword: 'createTime', name: '创建时间', timeType: 'daterange', labelWidth: '82px', type: 'rangeDate' },
        { keyword: 'authorizeStartTime', name: '合作期起', timeType: 'daterange', labelWidth: '82px', type: 'rangeDate' },
        { keyword: 'authorizeEndTime', name: '合作期止', timeType: 'daterange', labelWidth: '82px', type: 'rangeDate' },
        { keyword: 'incomeTime', name: '收入日期', timeType: 'daterange', labelWidth: '82px', type: 'rangeDate' }
      ];
    },
    tableOutsideHeight() {
      return 246;
    }
  },
  created() {
    this.fetchData(true);
    this.queryTagTreeList();
    this.getOrderConfig();
  },
  methods: {
    hasRouteAuth,
    formatParams() {
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      // 时间处理
      paramsRangeFormat(this.rangeKeyArr, params);
      params.page = this.page;
      params.perPage = this.perPage;
      params.sortType = this.sortType;
      params.sortName = this.sortName;
      if (params.tag && params.tag.length > 0) {
        params.tag = params.tag.join(',');
      }
      if (params.writeOffStatus && params.writeOffStatus.length > 0) {
        params.writeOffStatus = params.writeOffStatus.join(',');
      }
      return params;
    },
    fetchData(reset = false, isPage = false) {
      if (reset) this.page = 1;
      const params = this.formatParams();
      this.listLoading = true;
      getmengliIpLicense(params).then(res => {
        this.listLoading = false;
        if (res.code === 200) {
          if (res.data.items) {
            res.data.items.forEach(i => {
              if (i.ipAry) {
                const ip = [];
                i.ipAry.forEach(j => {
                  const name = `${j.ipFigure || '--'}/${j.ipSeries || '--'}`;
                  ip.push(name);
                });
                i.ipInfo = ip.join(',');
              }
            });
          }
          this.list = res.data;
          this.list.isInit = false;
          this.setSelectRow && this.setSelectRow(res.data.items);
        }
      }).catch(e => {
        this.listLoading = false;
      });
      if (!isPage) {
        this.getIpLicenseStatistics(params);
      }
    },
    // 获取萌力星球订单配置项
    async getOrderConfig() {
      try {
        const res = await getOrderConfig();
        this.areaList = res.data.areaList;
        this.themeList = res.data.themeList;
        this.areaList.map(el => {
          // eslint-disable-next-line no-sequences
          el.value = el.id,
          el.label = el.name;
        });
        this.themeList.map(el => {
          // eslint-disable-next-line no-sequences
          el.value = el.id,
          el.label = el.name;
        });
      } catch (error) {
        console.log(error);
      }
    },
    // 统计面板
    getIpLicenseStatistics(params) {
      this.statisticsLoading = true;
      getIpLicenseStatistics(params).then(res => {
        if (res.code === 200) {
          this.statisticsData = res.data;
        }
        this.statisticsLoading = false;
      }).catch(e => {
        this.statisticsLoading = false;
      });
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true, true);
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData(false, true);
    },
    // 查询
    queryClick() {
      this.fetchData(true);
    },
    // 排序
    sortMethod(a) {
      if (a.order) {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      } else {
        this.sortName = '';
        this.sortType = '';
      }
      this.fetchData(true, true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.fetchData(true);
    },
    // 操作
    toCreate() {
      this.$router.push({
        name: 'mengliOrderAdd',
        query: { type: 0 }
      });
    },
    toDetail(item) {
      this.$router.push({
        name: 'mengliOrderDetail',
        params: { id: item.id },
        query: { type: 0 }
      });
    },
    toEdit(item) {
      this.$router.push({
        name: 'mengliOrderEdit',
        params: { id: item.id },
        query: { type: 0 }
      });
    },
    toDel(item) {
      showModal('是否确定删除该订单', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        mengliOrderDel(item.id).then(res => {
          this.$message.success('删除成功');
          this.resetItemSelected(item.id);
          this.fetchData(true);
        }).catch(err => {
          console.error(err);
        });
      }).catch(() => {
        return false;
      });
    },
    exportBeforeExport() {
      this.dialogVisible = true;
    },
    closeDialog() {
      this.exportTime = '';
      this.dialogVisible = false;
    },
    queryTagTreeList() {
      const params = { type: this.TAG_MODULES.IMAGE_AUTH };
      getTagAll(params).then(res => {
        this.tagTreeList = (res && res.data) || [];
        this.tagTreeList.forEach(item => {
          if (!item.item) item.disabled = true;
        });
      }).catch(e => {
        console.log(e);
      });
    },
    // 导出
    handleExport() {
      const params = this.formatParams();
      if (this.exportTime && this.exportTime.length === 2) {
        params.exportStartTime = Math.round(this.exportTime[0] / 1000);
        params.exportEndTime = Math.round(this.exportTime[1] / 1000);
      }
      if (this.multipleSelectionAll.length) {
        params.ids = this.multipleSelectionAll.map(item => item.id).join(',');
      }
      this.closeDialog();
      if (this.showMobilePage) {
        if (this.$refs['moreOpeatorRef']) {
          this.$refs['moreOpeatorRef'].btnExport(params, 'templateExportRef');
        }
      } else {
        this.$refs['btnGroupRef'] && this.$refs['btnGroupRef'].btnExportDirect(params);
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.opeator-bar {
  position: absolute;
  right: 0;
  top: 0;
  display: flex;
  align-items: center;
}
.mengli-all-order {
  margin: 16px 16px 0 16px;
  background-color: #fff;
  padding: 20px 20px 55px 20px;
  .order-num {
    color: #406EFF;
  }
}
.el-dropdown-link {
  display: block;
  position: relative;
  padding-left:6px;
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    margin-top: -7px;
    width: 1px;
    background: #ddd;
    height: 14px;
  }
}
.data-picker-box {
  display: flex;
  justify-content: center;
  margin-bottom: 1.5em;
}
.dialog-footer {
  display: flex;
  justify-content: center;
}
.el-date-editor {
  width: 240px;
}
</style>
